package com.echo.boot.introspector;

import com.echo.boot.pojo.User;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/9/14
 * Time: 9:59
 * 内省机制
 *
 * @author Administrator
 */
public class IntrospectorTest {

    public static void main(String[] args) throws Exception {
        // //
        BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class);
        User user = User.class.newInstance();
        user.setId(20);
        user.setUsername("echo");
        user.setAge(19);
        user.setPassword("wertj457");
        user.setGender((byte) 1);
        user.setBirthday(LocalDateTime.now());
        user.setHobbies("football");


        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        System.out.println(user);

        for (PropertyDescriptor pd : descriptors) {
            System.out.println("属性名称：" + pd.getName());
            System.out.println("getter : " + pd.getReadMethod());
            System.out.println("setter : " + pd.getWriteMethod());
            System.out.println("___________________________________");
            if ("username".equals(pd.getName())) {
                Method setter = pd.getWriteMethod();
                setter.invoke(user, "jack");
            }

        }
//        System.out.println(user);

        Map<String, Object> map = beanToMap(user);
        map.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

        User toBean = mapToBean(map, user.getClass());
        System.out.println(toBean);

    }

    // 把JavaBean对象转换为Map
    public static Map<String, Object> beanToMap(Object bean) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            String key = pd.getName();
            Object value = pd.getReadMethod().invoke(bean);
            map.put(key, value);
        }
        return map;
    }

    // Map对象转换为JavaBean：
    public static <T> T mapToBean(Map<String, Object> map, Class<T> beanType) throws Exception {
        T instance = beanType.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(beanType, Object.class);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            Object value = map.get(pd.getName());
            pd.getWriteMethod().invoke(instance, value);
        }
        return (T) instance;
    }
}


